package com.xp.flow.component;

import com.yomahub.liteflow.annotation.LiteflowComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * 条件判断组件
 * 根据配置的表达式进行条件判断，支持流程分支控制
 * 
 * @author AI Assistant
 * @since 1.0.0
 */
@Slf4j
@LiteflowComponent("CONDITION")
public class ConditionComponent extends BaseFlowComponent {

    private final ExpressionParser parser = new SpelExpressionParser();

    @Override
    public void process() {
        // 验证必需配置
        validateRequiredConfig("expression");
        
        // 获取配置
        String expression = getConfigValue("expression", "true");
        String description = getConfigValue("description", "条件判断");
        
        logExecution("开始执行条件判断: %s, 表达式: %s", description, expression);
        
        // 获取输入数据
        Map<String, Object> inputData = getInputData();
        
        boolean result = false;
        try {
            // 创建表达式评估上下文
            StandardEvaluationContext context = new StandardEvaluationContext();
            
            // 将输入数据设置为上下文变量
            if (inputData != null) {
                for (Map.Entry<String, Object> entry : inputData.entrySet()) {
                    context.setVariable(entry.getKey(), entry.getValue());
                }
                // 设置input变量为整个输入数据
                context.setVariable("input", inputData);
            }
            
            // 解析并执行表达式
            Expression expr = parser.parseExpression(expression);
            Object evalResult = expr.getValue(context);
            
            // 转换结果为布尔值
            if (evalResult instanceof Boolean) {
                result = (Boolean) evalResult;
            } else if (evalResult instanceof Number) {
                result = ((Number) evalResult).doubleValue() != 0;
            } else if (evalResult instanceof String) {
                result = !((String) evalResult).isEmpty();
            } else {
                result = evalResult != null;
            }
            
            logExecution("条件判断结果: %s (原始值: %s)", result, evalResult);
            
        } catch (Exception e) {
            logError("条件表达式执行失败: " + expression, e);
            // 默认返回false
            result = false;
        }
        
        // 创建输出数据
        Map<String, Object> outputData = new HashMap<>(inputData);
        outputData.put("conditionResult", result);
        outputData.put("expression", expression);
        outputData.put("description", description);
        
        // 设置输出数据
        setOutputData(outputData);
        
        logExecution("条件判断组件执行完成，结果: %s", result);
    }
    
    /**
     * 获取条件判断结果
     * 用于LiteFlow的条件节点判断
     * 
     * @return 判断结果
     */
    public boolean isAccess() {
        // 执行条件判断逻辑
        process();
        
        // 从输出数据中获取结果
        Map<String, Object> outputData = getInputData();
        Object result = outputData.get("conditionResult");
        
        return result instanceof Boolean ? (Boolean) result : false;
    }
}